'use strict'
const path = require('path')
const fs2 = require('fs');
const os = require('os');

import { app, BrowserWindow, globalShortcut, ipcMain, protocol, screen } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'

app.commandLine.appendSwitch('enable-experimental-web-platform-features');

const ExcelJS = require('exceljs');
const { createObjectCsvWriter } = require('csv-writer');
const csv = require('csv-parser');

// const bluetooth = require('node-bluetooth');
// const device = new bluetooth.DeviceINQ();
// // 连接蓝牙  红外线 connect npm install irsdk
// // https://www.electronjs.org/zh/docs/latest/tutorial/devices
// // https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Bluetooth_API
// bluetooth.connect()
const PN = (process.env.GCML_LBA == undefined ? "error" : process.env.GCML_LBA)
const isDevelopment = process.env.NODE_ENV !== 'production'

app.allowRendererProcessReuse = false
protocol.registerSchemesAsPrivileged([
    { scheme: 'app', privileges: { standard: true, supportFetchAPI: true, secure: true, stream: true } }
])
if (process.env.NODE_ENV !== 'development') {
    global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow = null

async function createWindow(a, b) {
    const currentDisplay = screen.getPrimaryDisplay();
    // Create the browser window.
    mainWindow = new BrowserWindow({
        width: !process.env.WEBPACK_DEV_SERVER_URL ? a : 1920,
        height: !process.env.WEBPACK_DEV_SERVER_URL ? b : 1080,
        // width: currentDisplay.workAreaSize.width,
        // height: currentDisplay.workAreaSize.height,
        frame: false,
        x: 0,
        y: 0,
        useContentSize: true,
        resizable: process.env.WEBPACK_DEV_SERVER_URL,
        webPreferences: {
            contextIsolation: false,
            nodeIntegration: true,
            webSecurity: false,
            webviewTag: true,
            nodeIntegrationInWorker: true,
            alwaysOnTop: !process.env.WEBPACK_DEV_SERVER_URL
        },
    })

    // mainWindow.setFullScreen(true)
    // mainWindow.webContents.openDevTools()

    if (process.env.WEBPACK_DEV_SERVER_URL) {
        // Load the url of the dev server if in development mode
        await mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
        if (!process.env.IS_TEST) mainWindow.webContents.openDevTools()
    } else {
        createProtocol('app')
        // Load the index.html when not in development
        mainWindow.loadURL('app://./index.html')
    }

    globalShortcut.register('F6', () => {
        mainWindow.webContents.openDevTools()
    })


    mainWindow.webContents.on('select-bluetooth-device', async (event, deviceList, callback) => {
        // event.preventDefault()
        // const result = deviceList.find((device) => {
        //   // console.log(device)
        //   return device.deviceName === 'RFstar_A9A8'
        // })
        // if (!result) {
        //   // The device wasn't found so we need to either wait longer (eg until the
        //   // device is turned on) or cancel the request by calling the callback
        //   // with an empty string.
        //   callback('')
        // } else {
        //   callback(result.deviceId)
        // }
    });
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow(displays.workAreaSize.width, displays.workAreaSize.height)
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
    // if (isDevelopment && !process.env.IS_TEST) {
    //   // Install Vue Devtools
    //   try {
    //     await installExtension(VUEJS3_DEVTOOLS)
    //   } catch (e) {
    //     console.error('Vue Devtools failed to install:', e.toString())
    //   }
    // }
    // killjava()

    setTimeout(() => {
        const displays = screen.getPrimaryDisplay()
        createWindow(displays.workAreaSize.width, displays.workAreaSize.height)
    }, 300);
    // setTimeout(()=>{
    //   openBrain()
    // }, 550)
})


let javapid = -100
app.on('window-all-closed', function () {
    // // console.log("window-all-closed")
    // // javaProcess.kill("SIGTERM")
    // // const spawn = require('child_process').spawnSync
    // // spawn('taskkill -9 /f /t /im "java.exe"')
    // if(javaProcess != null)
    //     process.kill(javaProcess.pid)
    // if(javapid != -100)
    //     process.kill(javapid)

    // killjava()
})


//
app.on('before-quit', () => {
    // console.log("before-quit")
    // javaProcess.kill("SIGTERM")
    // const spawn = require('child_process').spawnSync
    // spawn('taskkill  -9 /f /t /im "java.exe"')
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', (data) => {
            if (data === 'graceful-exit') {
                setTimeout(() => {
                    app.quit()
                }, 200)
            }
        })
    } else {
        process.on('SIGTERM', () => {
            setTimeout(() => {
                app.quit()
            }, 200)
        })
    }
}

ipcMain.on('save-data-to-file', async (event, dataArray) => {
    try {
        // 获取当前时间作为文件名
        const now = new Date();
        const fileName = 'hat.txt';

        // 目标文件夹路径
        const folderPath = 'C:\\Hat';

        // 检查文件夹是否存在，不存在则创建
        if (!fs2.existsSync(folderPath)) {
            fs2.mkdirSync(folderPath, { recursive: true });
        }

        // 完整文件路径
        const filePath = path.join(folderPath, fileName);
        dataArray = JSON.parse(dataArray)
        const dataString = dataArray.data.map(item => JSON.stringify(item)).join(os.EOL)
        // 追加数据到文件，如果不存在则创建
        fs2.appendFileSync(filePath, dataString + os.EOL, 'utf8');

        return { success: true, message: '数据保存成功' };
    } catch (error) {
        console.error('保存文件时出错:', error);
        return { success: false, message: error.message };
    }
});

// import { EEGFatigueCalculator } from '@/eegFatigueCalculator';
// import { AttentionScoreMain } from '@/EEGAttentionScore';
// import { SleepStageServeMain } from '@/EEGSleepStageScore';
ipcMain.on('update-mental-fatigue', (event, brainwave) => {
    // // 在这里执行你的 Vue 代码
    // let temp1 = card.pilao.addDataPoint(brainwave);
    // let temp2 = card.zhuanzhu.calculateAttentionScore(brainwave);
    // let temp3 = card.shuiyi.outPutSleepStage(brainwave);

    // // 将结果发送回渲染进程
    // event.sender.send('update-mental-fatigue-response', { temp1, temp2, temp3 });
});